<?php
require_once __DIR__ . '/../../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    die('您没有权限访问此页面');
}

$orderId = intval($_GET['id'] ?? 0);

if ($orderId <= 0) {
    die('订单ID无效');
}

$db = getDB();

// 获取订单信息和用户详细信息
$stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name, u.wechat_account, u.alipay_account, u.wechat_nickname FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
$stmt->execute([$orderId]);
$order = $stmt->fetch();

if (!$order) {
    die('订单不存在');
}

// 获取订单操作记录
$operations = getOrderOperations($orderId);

// 获取群组名称标签
$groupNameLabel = getConfigOptionLabel('group_name', $order['group_name']);

// 生成防重复提交token
$formToken = md5(uniqid(mt_rand(), true) . $_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['form_tokens'])) {
    $_SESSION['form_tokens'] = [];
}
$_SESSION['form_tokens'][] = $formToken;
// 保持最近50个token
if (count($_SESSION['form_tokens']) > 200) {
    array_shift($_SESSION['form_tokens']);
}
?>
<style>
.enlargeable-image {
    transition: all 0.3s ease;
    cursor: zoom-in;
}

.enlargeable-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.image-container {
    position: relative;
    display: inline-block;
}

#previewImage {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
}

/* 加载动画 */
.img-loading {
    background: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
}
</style>
<style>
.clickable-image {
    transition: all 0.3s ease;
    cursor: pointer;
}

.clickable-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.image-container {
    position: relative;
    display: inline-block;
}
</style>
<form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate id="orderEditForm">
    <input type="hidden" name="form_token" value="<?php echo $formToken; ?>">
    <input type="hidden" name="action" value="update_status">
    <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
    
    <!-- 订单基本信息编辑 -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0"><i class="bi bi-pencil-square"></i> 编辑订单基本信息</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="product_name" class="form-label">商品名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="product_name" name="product_name" 
                                       value="<?php echo htmlspecialchars($order['product_name']); ?>" required>
                                <div class="invalid-feedback">请输入商品名称</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="delivery_location" class="form-label">收货地 <span class="text-danger">*</span></label>
                                <select class="form-select" id="delivery_location" name="delivery_location" required>
                                    <option value="">请选择收货地</option>
                                    <?php 
                                    $deliveryLocations = getConfigOptions('delivery_location');
                                    foreach ($deliveryLocations as $location): 
                                    ?>
                                        <option value="<?php echo $location['option_value']; ?>" 
                                                <?php echo $order['delivery_location'] == $location['option_value'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($location['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">请选择收货地</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="order_platform" class="form-label">下单平台 <span class="text-danger">*</span></label>
                                <select class="form-select" id="order_platform" name="order_platform" required>
                                    <option value="">请选择下单平台</option>
                                    <?php 
                                    $orderPlatforms = getConfigOptions('order_platform');
                                    foreach ($orderPlatforms as $platform): 
                                    ?>
                                        <option value="<?php echo $platform['option_value']; ?>" 
                                                <?php echo $order['order_platform'] == $platform['option_value'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($platform['option_label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="invalid-feedback">请选择下单平台</div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="tracking_no" class="form-label">物流单号</label>
                                <input type="text" class="form-control" id="tracking_no" name="tracking_no" 
                                       value="<?php echo htmlspecialchars($order['tracking_no']); ?>" placeholder="请输入物流单号">
                            </div>
                            
                            <div class="mb-3">
                                <label for="order_amount" class="form-label">下单金额 <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="order_amount" name="order_amount" 
                                       step="0.01" min="0" value="<?php echo $order['order_amount']; ?>" required>
                                <div class="invalid-feedback">请输入有效的订单金额</div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="payment_method" class="form-label">付款方式 <span class="text-danger">*</span></label>
                                <select class="form-select" id="payment_method" name="payment_method" required>
                                    <option value="owner_paid" <?php echo $order['payment_method'] == 'owner_paid' ? 'selected' : ''; ?>>自己付款</option>
                                    <option value="group_paid" <?php echo $order['payment_method'] == 'group_paid' ? 'selected' : ''; ?>>群主垫付</option>
                                </select>
                                <div class="invalid-feedback">请选择付款方式</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="order_notes" class="form-label">订单备注</label>
                        <textarea class="form-control" id="order_notes" name="order_notes" 
                                  rows="3" placeholder="请输入订单备注信息"><?php echo htmlspecialchars($order['notes'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="order_screenshot" class="form-label">更新订单截图</label>
                        <input type="file" class="form-control" id="order_screenshot" name="order_screenshot" 
                               accept="image/*">
                        <div class="form-text">支持 JPG、PNG、GIF 格式，最大 5MB</div>
                        
                        <?php if ($order['order_screenshot']): ?>
                            <div class="mt-2">
                                <small class="text-muted">当前截图：</small>
                                <a href="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                                   target="_blank" class="btn btn-sm btn-outline-info">
                                    <i class="bi bi-image"></i> 查看原图
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-6">
            <h6>用户信息</h6>
            <table class="table table-sm">
                <tr><td><strong>用户名：</strong></td><td><?php echo htmlspecialchars($order['username']); ?></td></tr>
                <tr><td><strong>手机号：</strong></td><td><?php echo htmlspecialchars($order['phone']); ?></td></tr>
                <tr><td><strong>群组：</strong></td><td><?php echo htmlspecialchars($groupNameLabel); ?></td></tr>
                <?php if ($order['wechat_account']): ?>
                    <tr><td><strong>微信账号：</strong></td><td><?php echo htmlspecialchars($order['wechat_account']); ?></td></tr>
                <?php endif; ?>
                <?php if ($order['wechat_nickname']): ?>
                    <tr><td><strong>微信昵称：</strong></td><td><?php echo htmlspecialchars($order['wechat_nickname']); ?></td></tr>
                <?php endif; ?>
                <?php if ($order['alipay_account']): ?>
                    <tr><td><strong>支付宝账号：</strong></td><td><?php echo htmlspecialchars($order['alipay_account']); ?></td></tr>
                <?php endif; ?>
            </table>
            
            <h6>当前状态</h6>
            <div class="mb-3">
                <span class="badge bg-<?php echo getOrderRegistrationClass($order['is_registered']); ?> fs-6 me-2">
                    <?php echo getOrderRegistrationText($order['is_registered']); ?>
                </span>
                <span class="badge bg-<?php echo getSettlementTypeClass($order['settlement_type']); ?> fs-6 me-2">
                    <?php echo getSettlementTypeText($order['settlement_type']); ?>
                </span>
                <span class="badge bg-<?php echo getOrderReturnClass($order['is_returned']); ?> fs-6 me-2">
                    <?php echo getOrderReturnText($order['is_returned']); ?>
                </span>
                <span class="badge bg-<?php echo getOrderSignClass($order['is_signed']); ?> fs-6">
                    <?php echo getOrderSignText($order['is_signed']); ?>
                </span>
            </div>
            
            <?php if ($order['status'] == 'settled' && $order['settlement_amount']): ?>
                <div class="mb-3">
                    <strong>结算金额：</strong>
                    <span class="text-success"><?php echo formatAmount($order['settlement_amount']); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($order['settlement_info']): ?>
                <div class="mb-3">
                    <strong>结算信息：</strong>
                    <p class="text-muted small"><?php echo nl2br(htmlspecialchars($order['settlement_info'])); ?></p>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- 在操作类型选择部分添加新的选项 -->
        <div class="mb-3">
            <label for="operation_type" class="form-label">操作类型</label>
            <select class="form-select" id="operation_type" name="operation_type">
                <option value="">请选择操作类型</option>
                <!-- 新增：修改订单信息选项 -->
                <option value="update_info">修改订单信息</option>
                <!-- 允许重复结算 -->
                <option value="register">登记订单</option>
                <option value="settle_principal">结本金</option>
                <option value="settle_commission">结本金+佣金</option>
                <?php if ($order['status'] != 'refunded'): ?>
                    <option value="return">退还订单</option>
                <?php endif; ?>
            </select>
            <div class="form-text">
                <?php if ($order['is_registered']): ?>订单已登记<?php endif; ?>
                <!-- 移除已结算提示，允许重复结算 -->
                <?php if ($order['status'] == 'refunded'): ?>订单已退还<?php endif; ?>
            </div>
        </div>
            
            <div class="mb-3" id="settlementFields" style="display: none;">
                <div class="mb-3">
                    <label for="settlement_amount" class="form-label">结算金额</label>
                    <input type="number" class="form-control" id="settlement_amount" name="settlement_amount" 
                           step="0.01" min="0" value="<?php echo $order['order_amount']; ?>" 
                           placeholder="留空则根据结算类型自动计算">
                    <div class="form-text">如果留空，将根据结算类型自动计算金额</div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="is_signed" class="form-label">签收状态</label>
                <select class="form-select" id="is_signed" name="is_signed">
                    <option value="">保持原状态</option>
                    <option value="0" <?php echo $order['is_signed'] == 0 ? 'selected' : ''; ?>>未签收</option>
                    <option value="1" <?php echo $order['is_signed'] == 1 ? 'selected' : ''; ?>>已签收</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label for="settlement_info" class="form-label">操作信息</label>
                <textarea class="form-control" id="settlement_info" name="settlement_info" 
                          rows="4" placeholder="请输入结算说明、备注等"><?php echo htmlspecialchars($order['settlement_info'] ?? ''); ?></textarea>
            </div>
            
            <div class="mb-3">
                <label for="settlement_screenshots" class="form-label">结算截图</label>
                <input type="file" class="form-control" id="settlement_screenshots" name="settlement_screenshots[]" 
                       accept="image/*" multiple>
                <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
                
                <!-- 图片预览区域 -->
                <div id="imagePreview" class="mt-2"></div>
            </div>
        </div>
    </div>
    
    <?php if ($order['order_screenshot']): ?>
    <div class="mb-4">
        <h6>订单截图</h6>
        <div class="image-container">
            <img src="<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>" 
                 class="img-fluid rounded border clickable-image" 
                 style="max-height: 200px; cursor: pointer;" 
                 onclick="openImageModal('<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>')"
                 alt="订单截图">
            <div class="mt-1">
                <small class="text-muted">点击图片可放大查看</small>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if ($order['settlement_screenshot']): ?>
    <div class="mb-4">
        <h6>结算截图</h6>
        <div class="image-container">
            <img src="<?php echo UPLOAD_URL . 'settlements/' . $order['settlement_screenshot']; ?>" 
                 class="img-fluid rounded border clickable-image" 
                 style="max-height: 200px; cursor: pointer;" 
                 onclick="openImageModal('<?php echo UPLOAD_URL . 'settlements/' . $order['settlement_screenshot']; ?>')"
                 alt="结算截图">
            <div class="mt-1">
                <small class="text-muted">点击图片可放大查看</small>
            </div>
        </div>
    </div>
<?php endif; ?>
    
    <!-- 操作记录 -->
    <?php if (!empty($operations)): ?>
        <div class="mb-4">
            <h6>操作记录</h6>
            <div class="table-responsive">
                <table class="table table-sm table-hover">
                    <thead>
                        <tr>
                            <th>操作时间</th>
                            <th>操作类型</th>
                            <th>操作金额</th>
                            <th>操作信息</th>
                            <th>操作员</th>
                            <th>截图</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($operations as $op): ?>
                            <tr>
                                <td><?php echo formatTime($op['created_at']); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo getOperationTypeClass($op['operation_type']); ?>">
                                        <?php echo getOperationTypeText($op['operation_type']); ?>
                                    </span>
                                </td>
                                <td><?php echo $op['operation_amount'] ? formatAmount($op['operation_amount']) : '-'; ?></td>
                                <td><?php echo $op['operation_info'] ? htmlspecialchars($op['operation_info']) : '-'; ?></td>
                                <td><?php echo htmlspecialchars($op['admin_name']); ?></td>
                                <td>
                                    <?php 
                                    if ($op['screenshots']) {
                                        $screenshots = json_decode($op['screenshots'], true);
                                        if (is_array($screenshots)) {
                                            foreach ($screenshots as $screenshot): 
                                    ?>
                                        <a href="<?php echo UPLOAD_URL . 'settlements/' . $screenshot; ?>" target="_blank" class="btn btn-sm btn-outline-info mb-1">
                                            <i class="bi bi-image"></i> 查看
                                        </a>
                                    <?php 
                                            endforeach;
                                        }
                                    } else {
                                        echo '-';
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
    
    <hr>
    
    <div class="alert alert-info">
        <i class="bi bi-info-circle"></i>
        <strong>说明：</strong>
        <ul class="mb-0 mt-2">
            <li>您可以修改订单的基本信息（商品名称、收货地、下单平台、物流单号、金额、付款方式等）</li>
            <li>可以更新订单截图和添加结算截图</li>
            <li>结算操作会将订单汇总到用户的待结账单中，在结算管理页面进行实际打款操作</li>
            <li>订单允许重复结算，但请谨慎操作</li>
        </ul>
    </div>
    
    <div class="text-end">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary" id="submitBtn">
            <i class="bi bi-save"></i> 保存更改
        </button>
    </div>
    
    
</form>

<script>
// 编辑订单表单专用功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('初始化编辑订单表单');
    
    // 结算字段显示控制
    const operationType = document.getElementById('operation_type');
    const settlementFields = document.getElementById('settlementFields');
    
    if (operationType && settlementFields) {
        operationType.addEventListener('change', function() {
            if (this.value === 'settle_principal' || this.value === 'settle_commission') {
                settlementFields.style.display = 'block';
            } else {
                settlementFields.style.display = 'none';
            }
        });
        
        // 初始状态
        if (operationType.value === 'settle_principal' || operationType.value === 'settle_commission') {
            settlementFields.style.display = 'block';
        }
    }
    
    // 文件预览
    const screenshotInput = document.getElementById('settlement_screenshots');
    if (screenshotInput) {
        screenshotInput.addEventListener('change', function(e) {
            const preview = document.getElementById('imagePreview');
            if (!preview) return;
            
            preview.innerHTML = '';
            
            const files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.className = 'img-thumbnail me-2 mb-2';
                        img.style.maxHeight = '100px';
                        preview.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                }
            }
        });
    }
    
    // 表单提交处理
    const form = document.getElementById('orderEditForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
            }
        });
    }
    
    console.log('编辑订单表单初始化完成');
});
</script>